package com.wzm.utils;

import com.wzm.entity.WmsTask;
import io.qameta.allure.Step;
import io.restassured.path.json.JsonPath;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.*;

public class Utils {

    public static boolean await(long ms) {
        return await(ms, null);
    }

    @Step("等待")
    public static boolean await(long ms, String message) {
        boolean result = false;
        String wholeMsg ="";
        try {
            wholeMsg = (message==null || message.isEmpty())? "sleep： " +ms:"sleep： " +ms+" for "+message;
//            System.out.println(wholeMsg);
            Thread.sleep(ms);
            result = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return  result;
    }

    public static String getImageDecoder(String base64Image) {
        // 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 将字节数组转换为BufferedImage
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        BufferedImage image = null;
        try {
            image = ImageIO.read(bis);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取验证码区域


        // 将图像转换为灰度图像
        BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                Color originalColor = new Color(image.getRGB(x, y));
                Color grayColor = new Color(originalColor.getRed(), originalColor.getGreen(), originalColor.getBlue());
                grayImage.setRGB(x, y, grayColor.getRGB());
            }
        }

        // 找到并读取图像中的文本
        Iterator<Color> colorIterator = new ArrayList<Color>(Arrays.asList(Color.BLACK, Color.WHITE)).iterator();
        StringBuilder sb = new StringBuilder();
        for (int x = 0; x < grayImage.getWidth(); x++) {
            for (int y = 0; y < grayImage.getHeight(); y++) {
                if (colorIterator.hasNext()){
                    Color currentColor = colorIterator.next();
                    if (currentColor == Color.BLACK && grayImage.getRGB(x, y) != currentColor.getRGB()) {
                        sb.append("#"); // Assume # is the character in the captcha
                    } else if (currentColor == Color.WHITE && grayImage.getRGB(x, y) != currentColor.getRGB()) {
                        sb.append("$"); // Assume $ is the character in the captcha (for a different captcha system)
                    }
                }

            }
        }
        String captcha = sb.toString(); // The captcha text
        System.out.println(captcha); // Print the captcha text
        return captcha;
    }

    public static String getImageDecoder2(String base64Image) {
        // 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);

        // 将字节数组转换为BufferedImage
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        BufferedImage image = null;
        try {
            image = ImageIO.read(bis);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取验证码区域
        int startX = 0; // 验证码区域左上角x坐标
        int startY = 0; // 验证码区域左上角y坐标
        int width = 100; // 验证码区域宽度
        int height = 50; // 验证码区域高度
        BufferedImage captchaImage = image.getSubimage(startX, startY, width, height);

        BufferedImage grayImage = new BufferedImage(captchaImage.getWidth(), captchaImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = grayImage.createGraphics();
        g.drawImage(captchaImage, 0, 0, null);
        g.dispose();

        int threshold = 128; // 二值化阈值
        for (int i = 0; i < grayImage.getWidth(); i++) {
            for (int j = 0; j < grayImage.getHeight(); j++) {
                int rgb = grayImage.getRGB(i, j);
                int gray = (rgb >> 16) & 0xff;
                if (gray < threshold) {
                    grayImage.setRGB(i, j, 0x000000);
                } else {
                    grayImage.setRGB(i, j, 0xffffff);
                }
            }
        }

        StringBuilder captchaBuilder = new StringBuilder();
        int gap = 5; // 字符间隔
        int startPixelX = 5; // 第一个字符起始像素点x坐标
        int pixelY = 5; // 字符像素点y坐标
        int charWidth = 10; // 字符宽度
        int charHeight = 20; // 字符高度
        int charNum = 4; // 字符个数
        for (int i = 0; i < charNum; i++) {
            int charPixelX = startPixelX + (charWidth + gap) * i;
            BufferedImage charImage = grayImage.getSubimage(charPixelX, pixelY, charWidth, charHeight);
            // 对验证码字符图片进行识别或处理
            // ...
            // 将识别结果添加到验证码字符串构造器中
//            captchaBuilder.append();
        }
        String captcha = captchaBuilder.toString();
        return captcha;
    }

    public static Double moveUnixTime(double ms){
        long unixTimestamp = Instant.now().toEpochMilli();
        return unixTimestamp+ms;
    }

    /*
    * */
    public static String extractToStr(String response, String param){

        JsonPath jsonPath = new JsonPath(response);
        String name = jsonPath.getString(param);

        return name;
    }

    public static int extractToInt(String response, String param){
        JsonPath jsonPath = new JsonPath(response);
        int name = jsonPath.getInt(param);

        return name;
    }

    public static int findBestSolution1(int price, int number, int amount){

        List<Integer> convertibility = new ArrayList<>();
        int count = 0;
        convertibility.add((int) Math.floor(amount / price)); // 把第一次买的瓶数放到列表中
        //根据列表第一个数进行兑换以此类推
        for (int i = 0; i < convertibility.size(); i++) {
            int tmp = (int) Math.floor(convertibility.get(i) / number);
            if (tmp != 0){
                convertibility.add(tmp);
                System.out.println(convertibility);
            }
        }

        //统计总数
        for (int i = 0; i < convertibility.size(); i++) {
            count += convertibility.get(i);
        }
        return count;
    }

    /**
     * 练习，计算最多喝水数
     * price：单价，num:num个可以兑换一瓶，money:初始金额
     */
    public static int findBestSolution2(double price, int num, double money){

        int a = 0;  //固定第一次购买数
        int bottleCount = 0; // 初始化购买的瓶数
        int freeBottleCount = 0; // 初始化免费瓶数


        //初始钱可以购买数
        while (money >= price){
            bottleCount++;
            a++;
            money -= price;
        }

        //计算可以免费兑换数
        while (bottleCount >= num){  //每num个可兑换一瓶水
            int tmp = (int) Math.floor(bottleCount / num);  //出现小数时取整数部分
            freeBottleCount += tmp;
            bottleCount -= tmp;
        }
        System.out.println(freeBottleCount);
        System.out.println(bottleCount);
        System.out.println(a);
        return a + freeBottleCount;
    }

    public static int getMaxBottles(double n, int m, double j) {

        int bottles = (int) Math.floor(j / n); // 先用j元买水，可以买到的瓶数为j/n

        double remainingMoney = j % n; // 计算剩下的钱

        int exchangedBottles = remainingMoney == 0 ? bottles : (int) Math.floor((remainingMoney + n - 1) / n); // 如果剩下的钱还可以再买一瓶水，那么交换的瓶数为(remainingMoney + n - 1)/n,否则为bottles

        return bottles + exchangedBottles; // 总瓶数为先买的瓶数加上交换的瓶数

    }

    public static void checkSrt(String input) {

        for (int i = 0; i < input.length(); i++) {
             char chars = (char) input.indexOf(i);
        }
    }


    public static void main(String[] args) {

//        System.out.println(Utils.findBestSolution1(1,2,20));
//        System.out.println(Utils.findBestSolution2(1,2,20));
//        System.out.println(getMaxBottles(1,2,20));
//        List<T> l = new ArrayList<T>();
//        l.add("123");
//        l.add("fd");
//        checkList();
        WmsTask wmsTask = new WmsTask();
        String string = "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAjAGkDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1d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